const db = require('../dal/mongo')
const createToken = require('../utils/createToken')
const ObjectId = require('mongodb').ObjectId
class UserController{
    static async login (ctx, next) {
        const data = ctx.query
        const res = await db.find('account', data, {username: 1}).catch( err => {
            ctx.throw(500, '未找到数据')
        })
        console.log(res)
        if(res.length > 0){
            const token = await createToken(res._id)
            ctx.success({
                msg: '登录成功',
                data: res[0],
                success: true,
                token: token
            })
        }else{
            ctx.throw(400,'登录失败')
        }
    }
    static async getUserInfo (ctx) {
        const res = await db.find('account',{_id: ObjectId(ctx.query._id)},{password:0})
        if(res.length > 0){
            ctx.success({
                data: res[0],
                success: true
            })
        }else{
            ctx.throw(400,'failed')
        }
    }
    static async getAllUserInfo(ctx){
        const res = await db.find('account',{},{password:0,_id:0})
        if(res.length > 0) {
            ctx.success({
                data: res,
                success: true
            })
        }
    }
}
module.exports = UserController